package leetcode.tree;

import java.util.LinkedList;
import java.util.Queue;

public class PopulatingNextRightPointersInEachNode116 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };

    class Solution1 {
        public Node connect(Node root) {
            if (root == null || root.left == null) {
                return root;
            }
            Queue<Node> queue = new LinkedList<>();
            queue.add(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                while (size-- != 0) {
                    Node poll = queue.poll();
                    if (size != 0) {
                        poll.next = queue.peek();
                    }
                    if (poll.left != null) {
                        queue.add(poll.left);
                    }
                    if (poll.right != null) {
                        queue.add(poll.right);
                    }
                }
            }
            return root;
        }
    }

    //2
    class Solution2 {
        public Node connect(Node root) {
            if (root == null || (root.left == null && root.right == null)) {
                return root;
            }
            Queue<Node> queue = new LinkedList<>();
            queue.add(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                while (size-- != 0) {
                    Node poll = queue.poll();
                    if (size != 0) {
                        poll.next = queue.peek();
                    } else {
                        poll.next = null;
                    }
                    if (poll.left != null) {
                        queue.add(poll.left);
                    }
                    if (poll.right != null) {
                        queue.add(poll.right);
                    }
                }
            }
            return root;
        }
    }
}
